﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace IssueIT.Core.Domain.Model
{
	public class Project : IEntity
	{
		private readonly IList<Issue> _issues = new List<Issue>();
		private readonly HashSet<Role> _roles = new HashSet<Role>();
		private readonly IDictionary<User, Role> _userRoleMap = new Dictionary<User, Role>();

		public Project(string title, User createdBy)
		{
			Title = title;
			Owner = CreatedBy = createdBy;
			CreatedAt = SystemTime.Now;
			_roles.Add(Role.Owner);
			_userRoleMap.Add(createdBy, Role.Owner);
		}

		public Guid Id { get; set; }
		public string Title { get; private set; }
		public string UriName { get; set; }
		public User Owner { get; private set; }
		public User CreatedBy { get; private set; }
		public DateTime CreatedAt { get; private set; }

		public IEnumerable<Issue> Issues
		{
			get
			{
				return _issues;
			}
		}

		public IEnumerable<User> Users
		{
			get
			{
				return _userRoleMap.Keys;
			}
		}

		public IEnumerable<Role> Roles
		{
			get
			{
				return _roles;
			}
		}

		public void AddRole(Role newRole)
		{
			_roles.Add(newRole);
		}

		public IEnumerable<User> FindUserByRole(Role role)
		{
			return from userRole in _userRoleMap
				where userRole.Value==role
				select userRole.Key;
		}

		public IEnumerable<Tuple<User, Role>> GetUsersWithRoles()
		{
			return _userRoleMap.Select(x => Tuple.Create(x.Key, x.Value));
		}
	}
}